<?php

namespace app\controller\sdkapi;

use app\BaseController;
use think\facade\Db;
use app\common\validate\BaseValidate;
use think\exception\ValidateException;
use app\middleware\AuthComment;
use EasyWeChat\Factory;

/**
 * @api 其他
 * @AuthComment loginModels ["Admin","User"]
 */
class Other extends BaseController
{
	protected $middleware = [
		AuthComment::class,
	];

	/**
	 * @api 设置列表字段
	 * @AuthComment loginModels ["Admin"]
	 * @param string $model 模型名
	 * @param string $id id
	 * @param string $field 字段名
	 * @param string $value 值
	 */
	public function setModelField($model = '', $id = '', $field = '', $value = '')
	{
		Db::startTrans();
		try {
			$model_namespace = "app\model\\" . $model;
			$data = (new $model_namespace)->find($id);
			if (!$data) return failed('该数据不存在');

			$data->save([
				$field => $value
			]);
			Db::commit();
		} catch (\Exception $e) {
			Db::rollback();
			return failed($e->getMessage());
		}

		return success($data->$field);
	}

	/**
	 * @api 获取模型枚举字典
	 * @AuthComment loginModels []
	 * @param string $model 模型名
	 * @param string $field 枚举字段名，例如：status_map
	 */
	public function getModelMap($model = '', $field = '')
	{
		validate()->check(compact('model', 'field'), [
			'model|模型名' => 'require',
			'field|字段名' => 'require',
		]);

		$modelName = "app\model\\" . $model;
		if (!class_exists($modelName)) return failed('模型不存在');

		$fieldName = $modelName . '::' . $field;
		if(!defined($fieldName)) return failed('常量不存在');

		return success(constant($fieldName));
	}

	/**
	 * @api 获取小程序二维码
	 * @param string $scene 场景值
	 * @param string $optional 数组[page,width]
	 * @param string $show_img 是否直接响应图片
	 * @return void
	 */
	public function getAppCode($scene = '', $optional = '[]', $show_img = '')
	{
		$app = app('use_wechat')->getMiniApp();
		$response = $app->app_code->getUnlimit($scene, array_merge([
			// 'page'  => 'pages/index/index',
			'width' => 600,
		], json_decode($optional, true)));
		if (is_array($response) && isset($response['errcode'])) return failed($response['errcode'] . ':' . $response['errmsg']);

		$image = $response->getBodyContents();
		if ($show_img) {
			return response($image, 200, ['Content-Length' => strlen($image)])->contentType('image/png');
		}

		$imginfo = getimagesizefromstring($image);
		$base64String = 'data:' . $imginfo['mime'] . ';base64,' . chunk_split(base64_encode($image));
		$base64String = str_replace(array("\r\n"), "", $base64String);
		// echo '<img src="' . $base64String . '">';
		return success($base64String);
	}
}
